package cn.cdutetc.foxwatch.controller;

import cn.cdutetc.foxwatch.pojo.Result;
import cn.cdutetc.foxwatch.serveice.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 王勇
 * @ClassName： FileController
 * @ClassPath： cn.cdutetc.foxwatch.controller.FileController
 * @Description：
 * @date 2024/10/8 08:52
 */
@Controller
@RequestMapping("/upload")
@CrossOrigin
public class FileController {
    @Autowired
    FileService fileService;
    // TODO: 这是以流的形式获取文件与静态一致，但是稍微复杂一点
//    @GetMapping("/{fileName}")
//    public Result getFileByName(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
//        String upload = ResourceUtils.getURL("upload").getPath();
//        File file = new File(upload + File.separator + fileName);
//        try (FileInputStream fileInputStream = new FileInputStream(file);
//             OutputStream outputStream = response.getOutputStream()) {
//            byte[] buffer = new byte[4096];
//            int bytesRead;
//            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, bytesRead);
//            }
//        }
//
//        return Result.success();
//    }

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        Boolean b = fileService.addFile(file);
        return b ? Result.success() : Result.error("上传失败");
    }
}
